package com.tanhua.sso.service;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author xukang
 * @date 2021-08-11 14:59
 */
@Service
public class SmsService {
    private static com.aliyun.dysmsapi20170525.Client client;

    @Autowired
    private RestTemplate restTemplate;
    private static String accessKeyId = "LTAI7kS0DPdbcF3a";

    private static String accessKeySecret = "odUwKEfKQqNVpZcV9EoIDKIZpamX0T";
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送验证码短信
     * *
     *
     * @param mobile
     */
    public String sendSms(String mobile) {
        String url = "https://open.ucpaas.com/ol/sms/{function}";
        Map<String, Object> params = new HashMap<>();
        params.put("TemplateCode", "79146528c81ed8df157943698af6863f");
        params.put("token", "9e95300b895bcb8dfcf2d320cf37ba59");
        params.put("appid", "19d77cdc13d54579b80ff9bf63d59363");
//        params.put("SignName", "*****");
        params.put("PhoneNumbers", mobile);
// 生成4位数验证
        params.put("param", RandomUtils.nextInt(100000, 999999));
        ResponseEntity<String> responseEntity =
                this.restTemplate.postForEntity(url, params, String.class);
        String body = responseEntity.getBody();
        try {
            JsonNode jsonNode = MAPPER.readTree(body);
//000000 表示发送成功
            if (StringUtils.equals(jsonNode.get("code").textValue(),
                    "000000")) {
                return String.valueOf(params.get("param"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //    aiyun
    static {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            client = new com.aliyun.dysmsapi20170525.Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    public String senSms(String phone) throws Exception {
        String s = randomCode();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName("品优购")
                .setTemplateCode("SMS_150184969")
                .setTemplateParam("{\"code\":\"" + s + "\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

        return s;
    }

    public Map<String, Object> sendCheckCode(String phone) {

        Map<String, Object> result = new HashMap<>(2);
        try {
            String redisKey = "CHECK_CODE_" + phone;
            String value = this.redisTemplate.opsForValue().get(redisKey);
            if (StringUtils.isNotEmpty(value)) {
                result.put("code", 1);
                result.put("msg", "上一次发送的验证码还未失效");
                return result;
            }
            String code = this.senSms(phone);
            if (null == code) {
                result.put("code", 2);
                result.put("msg", "发送短信验证码失败");
                return result;
            }
//发送验证码成功
            result.put("code", 3);
            result.put("msg", "ok");
            //将验证码存储到Redis,2分钟后失效
            this.redisTemplate.opsForValue().set(redisKey, code,
                    Duration.ofMinutes(2));
            return result;
        } catch (Exception e) {
            result.put("code", 4);
            result.put("msg", "发送验证码出现异常");
            return result;
        }
    }
}

